package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.Constants;
import com.hmdp.utils.RedisCache;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 刷新token的拦截器
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private RedisCache redisCache;

    public RefreshTokenInterceptor(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    // 目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constants.AUTHORIZATION);
        if (ObjectUtil.isEmpty(token)) {
            return true;
        }

        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = redisCache.getHash(key);

        // 判断用户是否登录
        if (userMap.isEmpty()) {
            return true;
        } else {
            UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
            UserHolder.saveUser(userDTO);
            redisCache.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        }

        return true;
    }

    /**
     * 目标方法执行之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
